#include <sobjc-commons/defines.h>
#include "salloc.h"

typedef struct sblock *sblock_t;

struct sblock {
  void *buf;
  size_t len;
  BOOL lock;
  sblock_t next;
};

static sblock_t block_list = NULL;

void *
objc_salloc(size_t len)
{
  sblock_t block;

  block = block_list;
  while (block) {
    if (!block->lock) {
      block->lock = YES;
      if (len < block->len)
        return block->buf;
      else {
        block->len = len * 2;
        block->buf = objc_realloc(block->buf, block->len);
        return block->buf;
      }
    }
    block = block->next;
  }

  block = ALLOC(struct sblock);
  block->len = len * 2;
  block->buf = objc_malloc(block->len);
  block->lock = YES;
  block->next = NULL;
  block_list = block;
  return block->buf;
}

void
objc_sfree(void *p)
{
  sblock_t block;

  block = block_list;
  while (block) {
    if (block->buf == p) {
      block->lock = NO;
      return;
    }
    block = block->next;
  }
}

